package com.honghu.paylibrary

import android.app.Dialog
import android.app.DialogFragment
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.honghu.paylibrary.bean.PayTypeBean
import com.honghu.paylibrary.bean.WebPayBean
import com.honghu.paylibrary.enums.PayType
import com.honghu.paylibrary.http.HttpManager
import com.honghu.paylibrary.interfaces.PayEnd
import com.honghu.paylibrary.utils.SpannableStringUtils
import com.honghu.paylibrary.utils.ToastUtils
import com.honghu.paylibrary.utils.UrlHelp
import com.unionpay.UPPayAssistEx
import com.zhouyou.http.EasyHttp
import com.zhouyou.http.callback.SimpleCallBack
import com.zhouyou.http.exception.ApiException
import org.json.JSONObject
import java.util.*

/**
 * 创建日期 2021/4/19
 * 描述：
 */
class PayDialogFragment : DialogFragment() {
    private var mPayEnd: PayEnd? = null
    private var mWebPayBean: WebPayBean? = null
    fun setWebPayBean(webPayBean: WebPayBean?): PayDialogFragment {
        mWebPayBean = webPayBean
        return this
    }

    fun setPayEnd(payEnd: PayEnd?): PayDialogFragment {
        mPayEnd = payEnd
        return this
    }

    private var mContext: Context? = null
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        mContext = activity
        val dialog = Dialog(mContext!!)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) // 设置Content前设定
        dialog.setContentView(R.layout.dialog_fragment_pay)
        dialog.setCanceledOnTouchOutside(true) // 外部点击取消
        dialog.setCancelable(false)
        // 设置宽度为屏宽, 靠近屏幕底部。
        val window = dialog.window
        window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT // 宽度持平
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        window.attributes = lp
        initView(dialog)
        return dialog
    }

    private fun initView(view: Dialog) {
        if (mWebPayBean == null) {
            dismiss()
            return
        }
        val ivClose = view.findViewById<View>(R.id.iv_close)
        ivClose.setOnClickListener { dismiss() }
        val list: MutableList<PayTypeBean> = ArrayList()
        mWebPayBean?.also {
            if (it.payTypeList.isNotEmpty()){
                for (i in it.payTypeList) {
                    list.add(PayTypeBean(i))
                    if (i == 0) {
                        list[0].isSelect = true
                    }
                }
            }
        }
        if (list.isEmpty()){
            for (i in 0..2) {
                list.add(PayTypeBean(i))
                if (i == 0) {
                    list[0].isSelect = true
                }
            }
            for (payTypeBean in list) {
                Log.d(TAG, "initView: " + payTypeBean.isSelect + " " + payTypeBean.value.desc)
            }
        }
        val payAdapter = PayAdapter(mContext, list)
        val recyclerView: RecyclerView = view.findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(mContext)
        recyclerView.adapter = payAdapter
        val tvMoney = view.findViewById<TextView>(R.id.tv_money)
        tvMoney.text = SpannableStringUtils.getBuilder(mContext, "¥").setProportion(0.6f).append(
            mWebPayBean!!.payMoney
        ).create()
        val tvPay = view.findViewById<TextView>(R.id.tv_pay)
        tvPay.setOnClickListener {
            var typeBean: PayTypeBean? = null
            for (payTypeBean in list) {
                if (payTypeBean.isSelect) {
                    typeBean = payTypeBean
                    break
                }
            }
            if (typeBean != null && typeBean.value == PayType.LIPAY_PAY) {
                tvPay.isEnabled = false
                tvPay.text = "支付中..."
                alipay(tvPay)
            } else if (typeBean != null && typeBean.value == PayType.YL_PAY) {
                tvPay.isEnabled = false
                tvPay.text = "支付中..."
                yinlianPay(tvPay)
            } else if (typeBean != null && typeBean.value == PayType.WE_CHAT_PAY) {
                tvPay.isEnabled = false
                tvPay.text = "支付中..."
                weiXinPay(tvPay)
            }
        }
    }

    private fun alipay(view: TextView) {
        mWebPayBean?.apply {
            val map: MutableMap<String, Any> = HashMap()
            map["userId"] = this.userId
            map["payMoney"] = this.payMoney
            map["diamondPrice"] = this.diamondPrice
            map["diamondNum"] = this.diamondNum
            map["giveDiamondNum"] = this.giveDiamondNum
            map["returnUrl"] = this.returnUrl
            val timeStamp = UrlHelp.getTimeStamp()
            map["timeStamp"] = timeStamp
            val set: MutableSet<String> = TreeSet()
            set.addAll(map.keys)
            map["sign"] = UrlHelp.getAppSign(map, set)
            HttpManager.post(UrlHelp.Pay.zfb_h5)
                .upJson(Gson().toJson(map))
                .also {
                    if (this.baseUrl.isNotEmpty()){
                        it.baseUrl(this.baseUrl)
                    }
                }
                .execute(object : SimpleCallBack<String>() {
                    override fun onError(e: ApiException) {
                        Log.e(TAG, "onError: ", e)
                        view.text = "立即付款"
                        view.isEnabled = true
                        ToastUtils.showToast(mContext, e.message)
                    }

                    override fun onSuccess(s: String) {
                        Log.d(TAG, "onSuccess: $s")
                        try {
                            val jsonObject = JSONObject(s)
                            val code = jsonObject.optInt(UrlHelp.CODE)
                            val msg = jsonObject.optString(UrlHelp.MSG)
                            if (code == 200) {
                                val data = jsonObject.optString(UrlHelp.DATA)
                                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(data))
                                startActivity(intent)
                                dismiss()
                            } else {
                                ToastUtils.showToast(mContext, msg)
                            }
                        } catch (e: Exception) {
                        } finally {
                            view.text = "立即付款"
                            view.isEnabled = true
                        }
                    }
                })
        }
        /*val map: MutableMap<String, Any> = HashMap()
        map["userId"] = mWebPayBean!!.userId
        map["payMoney"] = mWebPayBean!!.payMoney
        map["diamondPrice"] = mWebPayBean!!.diamondPrice
        map["diamondNum"] = mWebPayBean!!.diamondNum
        map["giveDiamondNum"] = mWebPayBean!!.giveDiamondNum
        map["returnUrl"] = mWebPayBean!!.returnUrl
        val timeStamp = UrlHelp.getTimeStamp()
        map["timeStamp"] = timeStamp
        val set: MutableSet<String> = TreeSet()
        set.addAll(map.keys)
        map["sign"] = UrlHelp.getAppSign(map, set)
        HttpManager.post(UrlHelp.Pay.zfb_h5)
            .upJson(Gson().toJson(map))
            .baseUrl(mWebPayBean!!.baseUrl)
            .execute(object : SimpleCallBack<String>() {
                override fun onError(e: ApiException) {
                    Log.e(TAG, "onError: ", e)
                    view.text = "立即付款"
                    view.isEnabled = true
                    ToastUtils.showToast(mContext, e.message)
                }

                override fun onSuccess(s: String) {
                    Log.d(TAG, "onSuccess: $s")
                    try {
                        val jsonObject = JSONObject(s)
                        val code = jsonObject.optInt(UrlHelp.CODE)
                        val msg = jsonObject.optString(UrlHelp.MSG)
                        if (code == 200) {
                            val data = jsonObject.optString(UrlHelp.DATA)
                            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(data))
                            startActivity(intent)
                            dismiss()
                        } else {
                            ToastUtils.showToast(mContext, msg)
                        }
                    } catch (e: Exception) {
                    } finally {
                        view.text = "立即付款"
                        view.isEnabled = true
                    }
                }
            })*/
    }

    private fun yinlianPay(view: TextView) {
        mWebPayBean?.apply {
            val map: MutableMap<String, Any> = HashMap()
            map["userId"] = this.userId
            map["payMoney"] = this.payMoney
            map["diamondPrice"] = this.diamondPrice
            map["diamondNum"] = this.diamondNum
            map["giveDiamondNum"] = this.giveDiamondNum
            map["returnUrl"] = this.returnUrl
            val timeStamp = UrlHelp.getTimeStamp()
            map["timeStamp"] = timeStamp
            val set: MutableSet<String> = TreeSet()
            set.addAll(map.keys)
            map["sign"] = UrlHelp.getAppSign(map, set)
            HttpManager.post(UrlHelp.Pay.yl_sdk)
                .upJson(Gson().toJson(map))
                .also {
                    if (this.baseUrl.isNotEmpty()){
                        it.baseUrl(this.baseUrl)
                    }
                }
                .execute(object : SimpleCallBack<String>() {
                    override fun onError(e: ApiException) {
                        Log.e(TAG, "onError: ", e)
                        view.text = "立即付款"
                        view.isEnabled = true
                        ToastUtils.showToast(mContext, e.message)
                    }

                    override fun onSuccess(s: String) {
                        Log.d(TAG, "onSuccess: $s")
                        try {
                            val jsonObject = JSONObject(s)
                            val code = jsonObject.optInt(UrlHelp.CODE)
                            val msg = jsonObject.optString(UrlHelp.MSG)
                            if (code == 200) {
                                val data = jsonObject.optString(UrlHelp.DATA)
                                val jsdata = JSONObject(data)
                                val tn = jsdata.getString("tn")
                                UPPayAssistEx.startPay(activity, null, null, tn, "00")
                                dismiss()

                            } else {
                                ToastUtils.showToast(mContext, msg)
                            }
                        } catch (e: Exception) {
                            Log.e(TAG, "onSuccess: ", e)
                        } finally {
                            view.text = "立即付款"
                            view.isEnabled = true
                        }
                    }
                })
        }
        /*val map: MutableMap<String, Any> = HashMap()
        map["userId"] = mWebPayBean!!.userId
        map["payMoney"] = mWebPayBean!!.payMoney
        map["diamondPrice"] = mWebPayBean!!.diamondPrice
        map["diamondNum"] = mWebPayBean!!.diamondNum
        map["giveDiamondNum"] = mWebPayBean!!.giveDiamondNum
        map["returnUrl"] = mWebPayBean!!.returnUrl
        val timeStamp = UrlHelp.getTimeStamp()
        map["timeStamp"] = timeStamp
        val set: MutableSet<String> = TreeSet()
        set.addAll(map.keys)
        map["sign"] = UrlHelp.getAppSign(map, set)
        HttpManager.post(UrlHelp.Pay.yl_sdk)
            .upJson(Gson().toJson(map))
            .baseUrl(mWebPayBean!!.baseUrl)
            .execute(object : SimpleCallBack<String>() {
                override fun onError(e: ApiException) {
                    Log.e(TAG, "onError: ", e)
                    view.text = "立即付款"
                    view.isEnabled = true
                    ToastUtils.showToast(mContext, e.message)
                }

                override fun onSuccess(s: String) {
                    Log.d(TAG, "onSuccess: $s")
                    try {
                        val jsonObject = JSONObject(s)
                        val code = jsonObject.optInt(UrlHelp.CODE)
                        val msg = jsonObject.optString(UrlHelp.MSG)
                        if (code == 200) {
                            val data = jsonObject.optString(UrlHelp.DATA)
                            val jsdata = JSONObject(data)
                            val tn = jsdata.getString("tn")
                            UPPayAssistEx.startPay(activity, null, null, tn, "00")
                            dismiss()

                        } else {
                            ToastUtils.showToast(mContext, msg)
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "onSuccess: ", e)
                    } finally {
                        view.text = "立即付款"
                        view.isEnabled = true
                    }
                }
            })*/
    }

    private fun weiXinPay(view: TextView) {
        mWebPayBean?.apply {
            val map: MutableMap<String, Any> = HashMap()
            map["userId"] = this.userId
            map["payMoney"] = this.payMoney
            map["diamondPrice"] = this.diamondPrice
            map["diamondNum"] = this.diamondNum
            map["giveDiamondNum"] = this.giveDiamondNum
            map["returnUrl"] = this.returnUrl
            val timeStamp = UrlHelp.getTimeStamp()
            map["timeStamp"] = timeStamp
            val set: MutableSet<String> = TreeSet()
            set.addAll(map.keys)
            map["sign"] = UrlHelp.getAppSign(map, set)
            HttpManager.post(UrlHelp.Pay.wx_sdk)
                .upJson(Gson().toJson(map))
                .also {
                    if (this.baseUrl.isNotEmpty()){
                        it.baseUrl(this.baseUrl)
                    }
                }
                .execute(object : SimpleCallBack<String>() {
                    override fun onError(e: ApiException) {
                        Log.e(TAG, "onError: ", e)
                        view.text = "立即付款"
                        view.isEnabled = true
                        ToastUtils.showToast(mContext, e.message)
                    }

                    override fun onSuccess(s: String) {
                        Log.d(TAG, "onSuccess: $s")
                        try {
                            val jsonObject = JSONObject(s)
                            val code = jsonObject.optInt(UrlHelp.CODE)
                            val msg = jsonObject.optString(UrlHelp.MSG)
                            if (code == 200) {
                                val data = jsonObject.optString(UrlHelp.DATA)
                                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(data))
                                startActivity(intent)
                                dismiss()
                            } else {
                                ToastUtils.showToast(mContext, msg)
                            }
                        } catch (e: Exception) {
                        } finally {
                            view.text = "立即付款"
                            view.isEnabled = true
                        }
                    }
                })
        }
        /*map["userId"] = mWebPayBean!!.userId
        map["payMoney"] = mWebPayBean!!.payMoney
        map["diamondPrice"] = mWebPayBean!!.diamondPrice
        map["diamondNum"] = mWebPayBean!!.diamondNum
        map["giveDiamondNum"] = mWebPayBean!!.giveDiamondNum
        map["returnUrl"] = mWebPayBean!!.returnUrl
        val timeStamp = UrlHelp.getTimeStamp()
        map["timeStamp"] = timeStamp
        val set: MutableSet<String> = TreeSet()
        set.addAll(map.keys)
        map["sign"] = UrlHelp.getAppSign(map, set)
        HttpManager.post(UrlHelp.Pay.wx_sdk)
            .upJson(Gson().toJson(map))
            .baseUrl(mWebPayBean!!.baseUrl)
            .execute(object : SimpleCallBack<String>() {
                override fun onError(e: ApiException) {
                    Log.e(TAG, "onError: ", e)
                    view.text = "立即付款"
                    view.isEnabled = true
                    ToastUtils.showToast(mContext, e.message)
                }

                override fun onSuccess(s: String) {
                    Log.d(TAG, "onSuccess: $s")

                    try {
                        val jsonObject = JSONObject(s)
                        val code = jsonObject.optInt(UrlHelp.CODE)
                        val msg = jsonObject.optString(UrlHelp.MSG)
                        if (code == 200) {
                            val data = jsonObject.optString(UrlHelp.DATA)
                            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(data))
                            startActivity(intent)
                            dismiss()
                        } else {
                            ToastUtils.showToast(mContext, msg)
                        }
                    } catch (e: Exception) {
                    } finally {
                        view.text = "立即付款"
                        view.isEnabled = true
                    }
                }
            })*/
    }

    companion object {
        private const val TAG = "PayDialogFragment"
    }
}